const { src, series, dest, parallel } = require('gulp')
const sass = require('gulp-sass');
const concat = require('gulp-concat');
const webpackStream = require('webpack-stream');
const path = require('path');
const del = require('del');
const rev = require('gulp-rev');
const revCol = require('gulp-rev-collector')



function copyHtml() {
  return src('./src/views/**/*.html')
    .pipe(dest('./dist/'))
  // todo...
}

function compileCSS() {
  return src('./src/style/**/*.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(concat('all.css'))
    .pipe(rev())//根据文件内容，生成带hash值得文件名
    .pipe(dest('./dist/'))
    .pipe(rev.manifest('css-rev-manifest.json'))
    .pipe(dest('./rev/'))
}


function compilejs() {
  return src('./src/js/app.js')
    .pipe(webpackStream({
      // 指定编译的模式，development 开发模式，production :生产模式，压缩，优化
      mode: "production",
      //打包的入口文件
      entry: {
        main: './src/js/app.js',
        detail: './src/js/Detail.js'
      },
      output: {
        //完整的输出目录
        path: path.resolve(__dirname, './dist/'),
        filename: '[name]-all.js'
      },
      module: {
        rules: [
          {
            //正则匹配
            test: /\.js$/,
            //排除的文件夹
            exclude: /node_modules/,
            use: {
              loader: 'babel-loader',
              options: {
                presets: ['@babel/preset-env'],//预设
                plugins: ['@babel/plugin-transform-runtime']
              }
            }
          }, {
            test: /\.html$/,
            loader: 'string-loader'
          }
        ]
      }

    }))
    .pipe(rev())
    .pipe(dest('./dist/'))
    .pipe(rev.manifest('js-rev-manifest.json'))
    .pipe(dest('./rev/'))
}


function copyLibs() {
  return src('./src/libs/**/*.*')
    .pipe(dest('./dist/libs/'))
}

function copyImages() {
  return src('./src/images/**/*.*')
    .pipe(dest('./dist/images/'))
}

function remove() {
  return del('./dist/')
}

function revColl() {
  return src(['./rev/*.json', './dist/*.html'])
    .pipe(revCol())
    .pipe(dest('./dist/'))

}


exports.default = series(remove, parallel(copyHtml, copyImages, copyLibs), compilejs, compileCSS, revColl);